package com.example.xushao.bbloadingview;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.Gravity;
import android.widget.FrameLayout;
import android.widget.ImageView;

/**
 * 加载动画
 *
 * @author shaojie.xu
 */
public class LoadingView extends FrameLayout {

    private static final int DEFAULT_COLOR = 0xFFFF4965;

    private final CircleView mCircleView;

    public LoadingView(Context context) {
        this(context, null);
    }

    public LoadingView(Context context, AttributeSet attrs) {
        super(context, attrs);

        DisplayMetrics metrics = getResources().getDisplayMetrics();
        final float defaultLogoSize = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 22f, metrics);
        final float defaultDiameter = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 50f, metrics);
        final float defaultStrokeWidth = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 2f, metrics);

        FrameLayout.LayoutParams logoLp = new FrameLayout.LayoutParams((int) defaultLogoSize, (int) defaultLogoSize);
        logoLp.gravity = Gravity.CENTER;

        ImageView logo = new ImageView(context);
        logo.setImageResource(R.drawable.ic_loading_img);
        addView(logo, logoLp);

        FrameLayout.LayoutParams circleLp = new FrameLayout.LayoutParams((int) defaultDiameter, (int) defaultDiameter);
        circleLp.gravity = Gravity.CENTER;

        mCircleView = new CircleView(context);
        addView(mCircleView, circleLp);

        if (attrs != null) {
            TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.LoadingView);
            int color = a.getInt(R.styleable.LoadingView_circle_color, DEFAULT_COLOR);
            float diameter = a.getDimension(R.styleable.LoadingView_circle_diameter, defaultDiameter);
            float strokeWidth = a.getDimension(R.styleable.LoadingView_stroke_width, defaultStrokeWidth);
            mCircleView.setColor(color);
            mCircleView.setDiameter(diameter);
            mCircleView.setStrokeWidth(strokeWidth);
            a.recycle();
        }
    }

    public void setColor(int color) {
        mCircleView.setColor(color);
    }

    public void setDiameter(float diameter) {
        mCircleView.setDiameter(diameter);
    }

    public void setStrokeWidth(float strokeWidth) {
        mCircleView.setStrokeWidth(strokeWidth);
    }

}
